package logic

import (
	"context"
	"encoding/json"
	"fmt"
	"manage/models/mysql"
	"manage/models/redis"
	"time"

	"manage/managerpc/internal/svc"
	"manage/managerpc/managerpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ActivityListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewActivityListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ActivityListLogic {
	return &ActivityListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 活动列表
func (l *ActivityListLogic) ActivityList(in *managerpc.ActivityListRequest) (*managerpc.ActivityListResponse, error) {
	// todo: add your logic here and delete this line
	offset := (in.Page - 1) * in.Size
	var user []mysql.Activity
	key := fmt.Sprintf("activity", in.UserId, in.Size)
	get := redis.Rdb.Get(l.ctx, key)
	if get.Val() == "" {
		mysql.DB.Offset(int(offset)).Limit(int(in.Size)).Order("created_at desc").Find(&user)
		marshal, _ := json.Marshal(user)
		redis.Rdb.Set(l.ctx, "activity", marshal, time.Hour*24)
	} else {
		json.Unmarshal([]byte(get.Val()), &user)
	}
	var Act []*managerpc.Lists
	for _, n := range user {
		list := managerpc.Lists{
			Id:     int64(n.ID),
			UserId: int64(n.UserId),
			Title:  n.Title,
			Image:  n.Image,
			Static: n.Static,
		}
		Act = append(Act, &list)
	}
	return &managerpc.ActivityListResponse{
		List: Act,
	}, nil
}
